package com.fingard.dsp.bank.directbank.gzdsf01;

import cfbs.api.CFBSConstant;
import cfbs.api.CFBSMsgUtil;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.IRealTime;
import com.fingard.dsp.bank.directbank.gzdsf01.util.CfbsAPI;
import com.fingard.dsp.bank.directbank.gzdsf01.util.CfbsUtils;
import com.fingard.dsp.bank.reqrespobj.single.ReqQrySingle;
import com.fingard.dsp.bank.reqrespobj.single.ReqSingle;
import com.fingard.dsp.bank.reqrespobj.single.RetAtsSingle;
import com.fingard.dsp.bank.reqrespobj.single.detail.RetAtsSglDetail;
import com.fingard.io.FileHelper;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;

import java.io.File;
import java.util.Date;

public class GZDSF01RealTime extends GZDSF01Base implements IRealTime {
	@Override
	public RetAtsSingle d_9108_RealTimeRec(ReqSingle p_req9108) throws Exception {
		RetAtsSingle retAts = new RetAtsSingle(p_req9108.reqHeader);
		RetAtsSglDetail tmpRetDetail = new RetAtsSglDetail();
		tmpRetDetail.reqSeqID = p_req9108.singleDetail.askNumber;
		try {
			StringBuilder tmpRealTimeSubmitRequest = new StringBuilder();
			tmpRealTimeSubmitRequest.append(GZDSF01TransCode.REALTIMEREC);// 交易种类
			tmpRealTimeSubmitRequest.append("1202");// 报文类型
			tmpRealTimeSubmitRequest.append(String.format("%16s", p_req9108.singleDetail.askNumber).replace(" ", "0"));// 交易序号
			tmpRealTimeSubmitRequest.append(Format.Date8Format.format(p_req9108.singleDetail.getPayDateTime()));// 委托日期
			tmpRealTimeSubmitRequest.append("00000000");// 清算日期

            String userNo = p_req9108.singleDetail.sourceNoteCode;
            if (StringHelper.isNullOrEmpty(userNo)) {
                userNo = p_req9108.singleDetail.authSeqID;
            }
            if (StringHelper.isNullOrEmpty(userNo)) {
                userNo = p_req9108.singleDetail.certNum;
            }
			tmpRealTimeSubmitRequest.append(String.format("%-18s", userNo));// 用户编号
			tmpRealTimeSubmitRequest.append(String.format("%-12s", bankFront.org));// 发起方代码（收费机构代码）
			tmpRealTimeSubmitRequest.append(String.format("%-12s", ""));// 发起方分支代码
			tmpRealTimeSubmitRequest.append(String.format("%-12s", getBankConfig().getMapValueByKey("bankBranchMapping", p_req9108.singleDetail.recAct)));// 发起方开户行行号（收费机构开户行行号）
			tmpRealTimeSubmitRequest.append(String.format("%-35s", p_req9108.singleDetail.recAct));// 发起方开户账号（收费机构开户账号）
            String outBank = this.getBankConfig().getMapAdvanceValuesExtra("outBankMapping", new String[]{"srcCode","srcArea"}, "value", new String[]{p_req9108.singleDetail.getOppBankCode(),p_req9108.singleDetail.getOppArea()});
            if(StringHelper.isNullOrEmpty(outBank)){
                outBank = this.getBankConfig().getMapAdvanceValue("outBankMapping", "srcCode", "value", p_req9108.singleDetail.getOppBankCode());
            }
            if(StringHelper.isNullOrEmpty(outBank)){
                this.WriteBankLogLn(p_req9108.singleDetail.getOppBankCode()+"-"+p_req9108.singleDetail.getOppArea()+"映射不到清算行号");
            }
			tmpRealTimeSubmitRequest.append(String.format("%-12s", outBank));// 接收方代码（付款清算行行号）
			tmpRealTimeSubmitRequest.append(String.format("%-12s", ""));// 接收方分支代码（付款人开户行行号）
			tmpRealTimeSubmitRequest.append(String.format("%-35s", p_req9108.singleDetail.payAct));// 付款人账号
			tmpRealTimeSubmitRequest.append(String.format(CfbsAPI.rightFill(p_req9108.singleDetail.payName, 60, " ")));// 付款人名称
			String businessTypes=getBankConfig().getValueAsString("businessTypes");
			if(StringHelper.isNullOrEmpty(businessTypes)) {
				businessTypes="00600";
			}
			tmpRealTimeSubmitRequest.append(businessTypes);// 业务种类
            String outBankPre = "";
            if(outBank.length()>=3){
                outBankPre = outBank.substring(0,3);
            }
			tmpRealTimeSubmitRequest.append(String.format("%-60s", CFBSMsgUtil.rightFill(CFBSConstant.FILL_WORD_BLANK_SPACE, 60, p_req9108.singleDetail.authCode)));// 合同（协议）号
			tmpRealTimeSubmitRequest.append(String.format("%-3s", convertCurToBank(p_req9108.singleDetail.payCur)));// 交易货币代码
			tmpRealTimeSubmitRequest.append(String.format("%15s", StringHelper.amountMultiply100(p_req9108.singleDetail.payAmount)).replace(" ", "0"));// 金额
			tmpRealTimeSubmitRequest.append(String.format("%15s", "").replace(" ", "0"));// 手续费
			tmpRealTimeSubmitRequest.append(String.format("%-60s", p_req9108.singleDetail.useType));// 附言
			tmpRealTimeSubmitRequest.append(String.format("%16s", "").replace(" ", "0"));// 业务处理方流水
			tmpRealTimeSubmitRequest.append(String.format("%-8s", ""));// 返回码
			tmpRealTimeSubmitRequest.append("0");// 主动缴费标识
			tmpRealTimeSubmitRequest.append(String.format("%8s", "4").replace(" ", "0"));// 变长定制信息长度
			tmpRealTimeSubmitRequest.append(String.format("%8s", "9108").replace(" ", "0"));// 变长定制信息长度
			tmpRealTimeSubmitRequest.append(String.format("%-64s", ""));// 校验码
			WriteBankLogLn("实时代扣请求报文生成摘要前明文数据:" + tmpRealTimeSubmitRequest.toString());
    		String tmpLoginRequest = new CfbsUtils(this.getSbLog()).txnEncSample(tmpRealTimeSubmitRequest.toString(), getEncryptKey(), getCharset());
    		sendToBank(tmpLoginRequest);
    		
    		tmpRetDetail.respCode = "0"; 
			tmpRetDetail.respInfo = "交易已受理!";
			tmpRetDetail.transState = "I4001";
			tmpRetDetail.payInfoCode = "I4001";
		} catch (Exception ex) {
			ex.printStackTrace();
			tmpRetDetail.respCode = "-1";
			tmpRetDetail.respInfo = ex.getMessage();
			WriteBankLogLn(ex);
		}
		
		retAts.writeRetDetail(tmpRetDetail);
		return retAts;
	}

	@Override
	public RetAtsSingle d_9144_QryRealTimeRec(ReqQrySingle p_req9144) throws Exception {
		RetAtsSingle retAts = new RetAtsSingle(p_req9144.reqHeader);
		RetAtsSglDetail tmpRetDetail = new RetAtsSglDetail();
		tmpRetDetail.reqSeqID = p_req9144.askNumber;
		
		try {
    	    File file = new File(getTempFileDirectory(p_req9144.getBgnDateTime()) + File.separator + "RealTimeRec" + File.separator + p_req9144.askNumber + ".txt");
    		WriteBankLogLn("本地单笔代扣查询结果文件路径:" + file.getAbsolutePath());
    		int index = 0;
    		while(true) {
    			++index;
    			Thread.sleep(1000);
    			System.out.println("第" + index + "秒后遍历单笔代扣查询结果文件是否存在:" + file.exists());
    			if (file.exists() || (index>500)) {
    				break;
    			}
    		}
    		if (file.exists()) {
				String tmpStrRet = FileHelper.readToString(file, getCharset());
				WriteBankLogLn("单笔代扣查询收到通知响应数据:\r\n" + tmpStrRet);
				StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet, tmpSbMsg);
                if (tmpBkReader != null) {
                	if (tmpBkReader.read("/ATSYH/TransResp/TransParam/DetailRecord")) {
                		tmpRetDetail.respCode = tmpBkReader.readedXElement.getSingleText("RespCode");
                		tmpRetDetail.respInfo = tmpBkReader.readedXElement.getSingleText("RespInfo");
                		tmpRetDetail.transState = tmpBkReader.readedXElement.getSingleText("TransState");
                		tmpRetDetail.payInfoCode = tmpBkReader.readedXElement.getSingleText("PayInfoCode");
                	}
                } else {
                    tmpRetDetail.respCode = "-1";
                    tmpRetDetail.respInfo = tmpSbMsg.toString();
                }
			} else {
				tmpRetDetail.respCode = "-1";
        		tmpRetDetail.respInfo = "记录不存在!";
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			tmpRetDetail.respCode = "-1";
			tmpRetDetail.respInfo = ex.getMessage();
			WriteBankLogLn(ex);
		}
		
		retAts.writeRetDetail(tmpRetDetail);
		return retAts;
	}
}
